﻿using Furion;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SqlSugar;

namespace Kevin.Code.Generator.DbAccessor
{
    /// <summary>
    /// Db访问器
    /// </summary>
    [AppStartup(11)]
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            var projectPath = Environment.CurrentDirectory.Replace(@"\bin\Debug", "").Replace(@"\net6.0-windows", "");
            var connectionString = $@"DataSource={projectPath}\db\codegenerator.sqlite";

            var connectionConfig = new ConnectionConfig {
                DbType = DbType.Sqlite,
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true,
                ConnectionString = connectionString
            };
            services.AddSqlSugar(connectionConfig,
            db =>
            {
                //处理日志事务
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Console.WriteLine(sql);
                    Console.WriteLine(string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));
                    Console.WriteLine();
                };

                //处理日志事务
                db.Aop.OnError = (sqlExe) =>
                {
                    var _logger = App.GetRequiredService<ILogger<Startup>>();
                    _logger.LogError(sqlExe.Sql);
                };
            });
        }
    }
}
